package org.fastsyncer.connector.sqlserver;

import org.fastsyncer.connector.config.DatabaseConfig;
import org.fastsyncer.connector.config.SqlConfig;
import org.fastsyncer.connector.constant.DatabaseConstant;
import org.fastsyncer.connector.database.AbstractDatabaseConnector;

public final class SqlServerConnector extends AbstractDatabaseConnector implements SqlServer {

    @Override
    public SqlConfig getSqlConfig(DatabaseConfig config, String table, String queryFilter) {
        // 查询元信息 SELECT TOP 0 * FROM USER
        String metaSQL = new StringBuilder().append("SELECT ").append(DatabaseConstant.SQLSERVER_PAGE_SQL_NULL).append(" * FROM ").append(table).toString();
        // 求数据总量 SELECT * FROM USER WHERE ID='123'
        String countSQL = new StringBuilder().append("SELECT * FROM ").append(table).append(queryFilter).toString();
        return new SqlConfig(metaSQL, countSQL);
    }

    @Override
    public String getPageSql(DatabaseConfig config, String table, String sql) {
        // SqlServer 分页查询
        // 获取主键
        String pk = config.getPrimaryKey();
        // sql> SELECT * FROM SD_USER
        // sql> SELECT * FROM SD_USER ORDER BY USER.ID OFFSET(3-1) * 1000 ROWS FETCH NEXT 1000 ROWS ONLY
        return new StringBuilder(sql).append(" ORDER BY ").append(table).append(".").append(pk).append(" OFFSET(?-1) * ? ROWS FETCH NEXT ? ROWS ONLY").toString();
    }

}
